/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "MapTileManager.h"
#include "WOWArchive.h"
#include "TerrainManager.h"
#include "SceneObject.h"

namespace PQGame
{
	MapTileManager::MapTileManager(int index)
		: _index(index),_tile(0)
	{
		initData();
		initTerrain();
	}
	
	void MapTileManager::initData()
	{
		WdtFile* wdt=SWOWArchive.getWdtFile(_index);
		WdlFile* wdl=SWOWArchive.getWdlFile(_index);

		int modf_count=wdt->modf_count;
		int time=1440;//set current time is 12:00

		for(int i=0;i<64;i++){
			for(int j=0;j<64;j++){
				int flag=wdt->map_tile_flag_table[i][j];
				if(flag){
					_hasTile[i][j] = true;
					_mapCount++;
				}else{
					_hasTile[i][j] = false;
				}
			}
		}

		//init using wdl
		_miniMap=wdl->mini_map;
	}

	void MapTileManager::initTerrain()
	{
		_terrainGlobalOptions = new Ogre::TerrainGlobalOptions();
		_terrainGlobalOptions->setMaxPixelError(8);
		_terrainGlobalOptions->setCompositeMapSize(1024);
		_terrainGlobalOptions->setCompositeMapDistance(3000);

		Ogre::SceneManager* sceneManager=PQEngine::SceneObject::getActive()->getSceneManager();
		_terrainGroup = new Ogre::TerrainGroup(sceneManager, Ogre::Terrain::ALIGN_X_Z, TILE_VERTICES, TILE_WORLD_SIZE);
		
	}

	MapTile *MapTileManager::loadTile(int col, int row)
	{
		if (!oktile(col,row) || !_hasTile[row][col]) {
			return 0;
		}

		int id=col+row*TILE_MAX;

		MapTileMap::iterator it= _tiles.find(id);
		if(it!=_tiles.end()){
			return it->second;
		}

		MapTile* tile=new MapTile(_index,col,row);
		_tiles.insert(MapTileMap::value_type(id,tile));

		return tile;
	}

	MapTile *MapTileManager::enterTile(int col, int row)
	{
		if(!oktile(col,row)){
			_outBound=true;	
		}else{
			_outBound=!_hasTile[row][col];
		}
		if(_outBound){
			return 0;
		}
		_col=col;
		_row=row;
		
		/*
		for (int j=0; j<3; j++) {
			for (int i=0; i<3; i++) {
				MapTile* tile=loadTile(col-1+i, row-1+j);
				initTileTerrain(tile);
			}
		}
		*/

		MapTile* tile=loadTile(col,row);
		initTileTerrain(tile);
		return tile;

	}

	void MapTileManager::initTileTerrain(MapTile* tile)
	{
		int row=tile->row();
		int col=tile->col();
		_terrainGroup->defineTerrain(0,0,tile->getHeights());
		_terrainGroup->loadTerrain(0,0,true);
		_terrainGroup->freeTemporaryResources();
	}

	void MapTileManager::update(float deltaT)
	{
		_terrainGroup->update();
	}

}

